﻿using UnityEngine;

public class EnemyTurret1 : EnemyBaseFixed
{
    
    [System.Serializable]
    public struct LookAtSprite
    {
        public LookAtDirection12 lookAtDirection;
        public Sprite sprite;
    }
    [Header("基础配置")]
    public LookAtSprite[] lookAtSpriteConfig;
    public float rotateIntervalTime = 1f;

    public SeqAction rotateAction = new() { intervalTime = 1f };

    private Vector2 targetDirection; 
    private SpriteRenderer sr;
    private Collider2D collider2d;


    private void Awake()
    {
        base.Init();
        sr = GetComponent<SpriteRenderer>();
        collider2d = GetComponent<Collider2D>();
        
        needTurnAround = false;
        lookAt = LookAtDirection12.Left.ToVector2();
    }
    void Start()
    {
        Run();
    }

    private void FixedUpdate()
    {
        base.CommonFixedUpdate();
    }

    protected virtual void UpdateStateNone(bool stateChanged, EnumState inState, out EnumState outState)
    {
        outState = inState;
        if (AllInViewPort())
        {
            outState = EnumState.Working;
        }
        collider2d.enabled = false;
        sr.sprite = GetLookAtSprite(LookAtDirection12.None);

    }
    protected void UpdateStateWorking(bool stateChanged, EnumState inState, out EnumState outState)
    {
        outState = inState;
        if (stateChanged)
        {
            rotateAction.ReStart();
            fireAction.ReStart();
        }
        if (!AllInViewPort())
        {
            outState = EnumState.None;
        }
        collider2d.enabled = true;

        if (Utility.GetNearestPlayerPosition(transform.position, out Vector2 nearestPlayerPosition))
        {
            Vector2 playerDirection = nearestPlayerPosition - new Vector2(transform.position.x, transform.position.y);
            targetDirection = playerDirection;
        }

        LookAtDirection12 target = targetDirection.ToLookAtDirection12();
        LookAtDirection12 current = lookAt.ToLookAtDirection12();
        rotateAction.Update((SeqAction seq) =>
        {

            if (target != current)
            {
                float angle = Vector2.SignedAngle(current.ToVector2(), target.ToVector2());
                if (angle > 0)
                {
                    lookAt = Quaternion.AngleAxis(30, Vector3.forward) * lookAt;
                }
                else
                {
                    lookAt = Quaternion.AngleAxis(-30, Vector3.forward) * lookAt;
                }
            }
        });
        if (target == current)
        {
            fireAction.Update((SeqAction seq) =>
            {
                if (seq.IsFirstAction())
                {
                    seq.PropertyInteger.Add("boxMagazine", boxMagazineSize);
                }
                int boxMagazine = seq.PropertyInteger["boxMagazine"];
                Fire();
                if (--boxMagazine <= 0)
                {
                    fireAction.ReStart();
                }
                else
                {
                    seq.PropertyInteger["boxMagazine"] = boxMagazine;
                }
            });
        }
        sr.sprite = GetLookAtSprite(lookAt.ToLookAtDirection12());
    }


    protected override void UpdateStateDie(bool stateChanged, EnumState inState, out EnumState outState)
    {
        base.UpdateStateDie(stateChanged,inState,out outState);
        if (boomPrefab != null)
        {
            Instantiate(boomPrefab, transform.position, Quaternion.identity);
        }
        Constant.Sounds.EnemyDeath2.PlayOneShot();
        Destroy(gameObject);

    }


    private Sprite GetLookAtSprite(LookAtDirection12 lookAtDirection)
    {
        Sprite ret = null;
        foreach (LookAtSprite config in lookAtSpriteConfig)
        {
            if (config.lookAtDirection == lookAtDirection)
            {
                ret = config.sprite;
                break;
            }
        }
        return ret;
    }

    private void Fire()
    {
        Vector2 position = transform.position;
        Vector2 offset = Vector3.zero;
        switch (lookAt.ToLookAtDirection12())
        {
            case LookAtDirection12.Left:
                offset += Vector2.left * 0.875f;
                break;
            case LookAtDirection12.LeftLeftUp:
                offset += Vector2.left * 0.875f + Vector2.up * 0.5f;
                break;
            case LookAtDirection12.UpLeftUp:
                offset += Vector2.left * 0.5f + Vector2.up * 0.8125f;
                break;
            case LookAtDirection12.Up:
                offset += Vector2.up * 0.875f;
                break;
            case LookAtDirection12.UpRightUp:
                offset += Vector2.right * 0.5f + Vector2.up * 0.8125f;
                break;
            case LookAtDirection12.RightRightUp:
                offset += Vector2.right * 0.875f + Vector2.up * 0.5f;
                break;
            case LookAtDirection12.Right:
                offset += Vector2.right * 0.875f;
                break;
            case LookAtDirection12.RightRightDown:
                offset += Vector2.right * 0.875f + Vector2.down * 0.5f;
                break;
            case LookAtDirection12.DownRightDown:
                offset += Vector2.right * 0.5f + Vector2.down * 0.8125f;
                break;
            case LookAtDirection12.Down:
                offset += Vector2.down * 0.875f;
                break;
            case LookAtDirection12.DownLeftDown:
                offset += Vector2.left * 0.5f + Vector2.down * 0.8125f;
                break;
            case LookAtDirection12.LeftLeftDown:
                offset += Vector2.left * 0.875f + Vector2.down * 0.5f;
                break;
        }
        position += offset;

        if (bulletPrefab != null)
        {
            GameObject objBullet = Instantiate(bulletPrefab, position, Quaternion.identity);
            if (objBullet.TryGetComponent<ABullet>(out var aBullet))
            {
                aBullet.SetBulletType(ABullet.BulletType.C);
                aBullet.SetSource(gameObject);
                aBullet.Launch(lookAt);
            }
        }
    }
}
